package com.learn.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/08/08
 * @description ch12 sentinel
 * SentinelResource注解的使用
 * 热点规则
 */
@RestController
public class ResourceLimitController {
    /**
     * 请求资源时，违反控流规则时触发blockHandler，发生异常时触发fallback
     * blockHandler，fallback 默认是本类中的同名方法，注意参数相同，防止重载
     * @param id
     * @return
     */
    @GetMapping("/resource/{id}")
    @SentinelResource(value = "resource", blockHandler = "blockHandlerMethod", fallback = "fallbackMethod")
    public String resource(@PathVariable("id") Integer id) {
        if(id < 1) {
            throw new RuntimeException("id < 1");
        }
        return "resource, id: " + id + "------------";
    }
    /**
     * 自定义限流处理
     * @param id
     * @param exception
     * @return
     */
    public String blockHandlerMethod(Integer id, BlockException exception) {
        return "blockHandler-----------";
    }
    /**
     * 自定义服务降级
     * @param id
     * @param e
     * @return
     */
    public String fallbackMethod(Integer id, Throwable e) {
        return "fallback-----------";
    }

    /**
     * 热点
     * @param
     * @return
     */
    @GetMapping("/hotpot")
    @SentinelResource(value = "hotPot", blockHandler = "blockHandlerMethod2", fallback = "fallbackMethod")
    public String hotPot(@RequestParam(value = "s1", required = false) String s1,
                         @RequestParam(value = "s2", required = false) String s2) {
        return "s1: " +  s1 + ",s2: " + s2;
    }

    public String blockHandlerMethod2(String s1, String s2, BlockException blockException) {
        return "blockHandlerMethod2---------";
    }
}














